package com.shinji.tratu;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;

import com.actionbarsherlock.widget.SearchView;

public class Util {

	public static final String TAG = "Util";
	public static final String MSERVER_LINK = "http://m.tratu.soha.vn/?title=";
	public static final String SERVER_LINK = "http://tratu.soha.vn/";

	public static ArrayList<Word> searchInListWordsByKey(
			ArrayList<Word> inputList, String key) {
		ArrayList<Word> outputList = new ArrayList<Word>();
		if (inputList == null || inputList.isEmpty())
			return outputList;
		for (Word word : inputList) {
			if (word.getKey().toLowerCase().contains(key.toLowerCase())) {
				outputList.add(word);
			}
		}
		return outputList;
	}

	public static Word searchInListWordsByKeyAndDicType(
			ArrayList<Word> listWords, String key, String dicType) {
		for (Word w : listWords) {
			if (w.getKey().equalsIgnoreCase(key)
					&& dicType.equals(w.getDicType())) {
				return w;
			}
		}
		return null;
	}

	/**
	 * tra ve link day du de tra tu
	 * 
	 * @param dicType
	 * @return
	 */
	public static String getLookupLink(String dicType, String keyLookup,
			boolean mobileOrNot) {
		// String url2 = "http://m.tratu.soha.vn/?title=angry&dict=en_en";
		// http://tratu.soha.vn/dict/en_vn/Back
		String utf8Query = Util.getUTF8HexCode(keyLookup);
		Log.i(TAG, "utf8Query = " + utf8Query);
		String encodedPath;
		if (utf8Query != null) {
			if (mobileOrNot) {
				encodedPath = MSERVER_LINK + utf8Query + "&dict=" + dicType;
			} else {
				encodedPath = SERVER_LINK + "dict/" + dicType + "/" + utf8Query;
			}
		} else {
			if (mobileOrNot) {
				encodedPath = MSERVER_LINK + keyLookup + "&dict=" + dicType;
			} else {
				encodedPath = SERVER_LINK + "dict/" + dicType + "/" + keyLookup;
			}
		}
		return encodedPath;
	}

	public static void hideSoftKeyboard(SearchView editText, Context context) {
		try {
			InputMethodManager imm = (InputMethodManager) context
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		} catch (Exception e) {
			Log.e(TAG, "" + e.toString());
		}
	}

	public static String getUnicodeValue(String line) {

		String hexCodeWithLeadingZeros = "";
		try {
			for (int index = 0; index < line.length(); index++) {
				String hexCode = Integer.toHexString(line.codePointAt(index))
						.toUpperCase();
				String hexCodeWithAllLeadingZeros = "0000" + hexCode;
				String temp = hexCodeWithAllLeadingZeros
						.substring(hexCodeWithAllLeadingZeros.length() - 4);
				hexCodeWithLeadingZeros += ("\\%" + temp);
				Log.i(TAG, "hexCode = " + hexCode + " , hexCodeAll = "
						+ hexCodeWithAllLeadingZeros + " , temp = " + temp);
			}
			return hexCodeWithLeadingZeros;
		} catch (NullPointerException nlpException) {
			return hexCodeWithLeadingZeros;
		}
	}

	public static String getNormalString(String unicodeString) {
		String str = unicodeString.split(" ")[0];
		str = str.replace("\\", "");
		String[] arr = str.split("u");
		String text = "";
		for (int i = 1; i < arr.length; i++) {
			int hexVal = Integer.parseInt(arr[i], 16);
			text += (char) hexVal;
		}
		return text;
	}

	public static String byteToHex(byte b) {
		// Returns hex String representation of byte b
		char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
		return new String(array);
	}

	public static String getUTF8HexCode(String plainText) {
		byte[] ptext;
		try {
			ptext = plainText.getBytes("UTF8");
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < ptext.length; i++) {
				sb.append("%").append(byteToHex(ptext[i]));
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	/**
	 * return name of dic
	 * 
	 * @param dicType
	 * @return
	 */
	public static String getDicNameFromType(Context context, String dicType) {
		String dicName = "";

		return dicName;
	}
	
	/**
	 * check network state
	 * @param context
	 * @return
	 */
	public static boolean isOnline(Context context) {
	    ConnectivityManager cm =
	        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
}
